<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-indigo-600 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <MapPin class="w-8 h-8 text-white" />
          </div>
          <CardTitle class="text-2xl text-slate-800">{{
            t("spatialMemoryTest.title")
          }}</CardTitle>
          <p class="text-slate-600 mt-2">
            {{ t("spatialMemoryTest.description") }}
          </p>
        </CardHeader>

        <CardContent class="space-y-6">
          <div
            class="bg-gradient-to-r from-indigo-50 to-purple-50 rounded-xl p-6 border border-indigo-100"
          >
            <h3
              class="font-semibold text-indigo-900 mb-4 flex items-center gap-2"
            >
              <Star class="w-5 h-5" />
              {{ t("spatialMemoryTest.instructionsTitle") }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >1</span
                >
                <p>{{ t("spatialMemoryTest.instruction1") }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >2</span
                >
                <p>{{ t("spatialMemoryTest.instruction2") }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >3</span
                >
                <p>{{ t("spatialMemoryTest.instruction3") }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >4</span
                >
                <p>{{ t("spatialMemoryTest.instruction4") }}</p>
              </div>
            </div>
          </div>

          <div class="bg-slate-50 rounded-xl p-4 border border-slate-200">
            <h4 class="font-semibold text-slate-700 mb-3 text-center">
              {{ t("spatialMemoryTest.testProcess") }}
            </h4>
            <div class="flex items-center justify-center gap-4">
              <div class="flex flex-col items-center text-center w-16">
                <Eye class="w-8 h-8 text-blue-500 mb-1" />
                <span class="text-xs text-slate-600">{{
                  t("spatialMemoryTest.observe")
                }}</span>
              </div>
              <div class="text-slate-400">→</div>
              <div class="flex flex-col items-center text-center w-16">
                <RotateCcw class="w-8 h-8 text-orange-500 mb-1" />
                <span class="text-xs text-slate-600">{{
                  t("spatialMemoryTest.wait")
                }}</span>
              </div>
              <div class="text-slate-400">→</div>
              <div class="flex flex-col items-center text-center w-16">
                <MapPin class="w-8 h-8 text-green-500 mb-1" />
                <span class="text-xs text-slate-600">{{
                  t("spatialMemoryTest.recall")
                }}</span>
              </div>
            </div>
          </div>

          <div class="grid md:grid-cols-3 gap-4">
            <div
              class="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200"
            >
              <div class="text-2xl font-bold text-indigo-600 mb-1">24</div>
              <div class="text-sm text-indigo-700">
                {{ t("spatialMemoryTest.trialsLabel") }}
              </div>
            </div>
            <div
              class="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200"
            >
              <div class="text-2xl font-bold text-purple-600 mb-1">8</div>
              <div class="text-sm text-purple-700">
                {{ t("spatialMemoryTest.difficultyLevels") }}
              </div>
            </div>
            <div
              class="text-center p-4 bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl border border-indigo-200"
            >
              <div class="text-2xl font-bold text-slate-600 mb-1">7</div>
              <div class="text-sm text-slate-700">
                {{ t("spatialMemoryTest.timeLimitLabel") }}
              </div>
            </div>
          </div>

          <Button
            class="w-full bg-gradient-to-r from-indigo-600 to-purple-500 hover:from-indigo-700 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
            size="lg"
            @click="handleStartTest"
          >
            {{ t("spatialMemoryTest.startTest") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div
    v-else-if="stage === 'test' && currentTrialData"
    class="max-w-4xl mx-auto space-y-6"
  >
    <transition appear name="fade">
      <div>
        <div
          class="flex flex-col sm:flex-row gap-4 items-center justify-between"
        >
          <div class="flex items-center gap-4 flex-wrap">
            <Badge
              class="bg-indigo-100 text-indigo-700 border-indigo-300"
              variant="outline"
              >{{ t("spatialMemoryTest.trial") }} {{ currentTrial + 1 }} /
              {{ trials.length }}
            </Badge>
            <Badge
              class="bg-purple-100 text-purple-700 border-purple-300"
              variant="outline"
              >{{ t("spatialMemoryTest.level") }} {{ currentLevel }}
            </Badge>
            <Badge :class="memoryPhaseClass" variant="outline">{{
              memoryPhaseText
            }}</Badge>
            <div class="flex items-center gap-2 text-slate-600">
              <Trophy class="w-4 h-4" />
              <span class="font-semibold">{{ score }}</span>
            </div>
          </div>
          <div class="flex items-center gap-2">
            <Clock class="w-4 h-4 text-slate-500" />
            <span
              :class="[
                'font-mono text-lg font-bold',
                timeLeft <= 60 ? 'text-red-500' : 'text-slate-700',
              ]"
            >
              {{ Math.floor(timeLeft / 60) }}:{{
                (timeLeft % 60).toString().padStart(2, "0")
              }}
            </span>
          </div>
        </div>

        <Progress :model-value="progress" class="h-2" />

        <Card
          :class="['bg-gradient-to-r', instructionCardClass]"
          style="margin: 24px 0"
        >
          <CardContent class="py-4 px-6">
            <div class="text-center">
              <h3 :class="['text-lg font-semibold', instructionTextClass]">
                {{ instructionText }}
              </h3>
              <p
                v-if="memoryPhase === 'recalling'"
                class="text-sm text-slate-600 mt-1"
              >
                {{ t("spatialMemoryTest.selected") }}:
                {{ selectedItems.length }} /
                {{ currentTrialData.targets.length }}
              </p>
            </div>
          </CardContent>
        </Card>

        <Card class="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardContent class="py-12">
            <div class="grid grid-cols-4 gap-3 max-w-md mx-auto">
              <transition-group name="fade">
                <button
                  v-for="item in grid"
                  :key="item.id"
                  :class="[
                    'w-16 h-16 rounded-lg border-2 transition-all duration-200',
                    gridItemClass(item),
                  ]"
                  :disabled="memoryPhase !== 'recalling'"
                  @click="handleGridClick(item)"
                >
                  <span
                    v-if="item.clicked"
                    class="text-white font-bold text-xl"
                    >{{ selectedItems.indexOf(item.id) + 1 }}</span
                  >
                </button>
              </transition-group>
            </div>
          </CardContent>
        </Card>
      </div>
    </transition>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-indigo-600 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Trophy class="w-10 h-10 text-white" />
          </div>
          <CardTitle class="text-3xl text-slate-800 mb-2">{{
            t("spatialMemoryTest.testComplete")
          }}</CardTitle>
          <div
            class="text-6xl font-bold bg-gradient-to-r from-indigo-600 to-purple-500 bg-clip-text text-transparent"
          >
            {{ results.finalScore }}
          </div>
          <p class="text-slate-600">
            {{ t("spatialMemoryTest.spatialMemoryScore") }}
          </p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="grid grid-cols-2 gap-4">
            <div
              class="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200"
            >
              <div class="text-2xl font-bold text-indigo-600 mb-1">
                {{ results.spatialMemorySpan }}
              </div>
              <div class="text-sm text-indigo-700">
                {{ t("spatialMemoryTest.memorySpan") }}
              </div>
            </div>
            <div
              class="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200"
            >
              <div class="text-2xl font-bold text-purple-600 mb-1">
                {{ results.accuracy }}%
              </div>
              <div class="text-sm text-purple-700">
                {{ t("spatialMemoryTest.accuracy") }}
              </div>
            </div>
          </div>
          <div class="space-y-3">
            <div
              class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
            >
              <span class="text-slate-600">{{
                t("spatialMemoryTest.correctSequences")
              }}</span>
              <span class="font-semibold text-slate-800"
                >{{ results.correctSequences }}/{{ trials.length }}</span
              >
            </div>
            <div
              class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
            >
              <span class="text-slate-600">{{
                t("spatialMemoryTest.highestLevel")
              }}</span>
              <span class="font-semibold text-slate-800">{{
                results.maxLevel
              }}</span>
            </div>
            <div
              class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
            >
              <span class="text-slate-600">{{
                t("spatialMemoryTest.totalScore")
              }}</span>
              <span class="font-semibold text-slate-800">{{ score }}</span>
            </div>
          </div>
          <Button
            class="w-full bg-gradient-to-r from-indigo-600 to-purple-500 hover:from-indigo-700 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg"
            size="lg"
            @click="handleComplete"
          >
            {{ t("spatialMemoryTest.viewDetailedResults") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { MapPin, Clock, Trophy, Star, Eye, RotateCcw } from "lucide-vue-next";
import { useGlobalI18n } from "~/composables/useGlobalI18n";

const { t } = useGlobalI18n();

const emit = defineEmits(["complete"]);

// --- State ---
const stage = ref("instructions"); // 'instructions', 'test', 'results'
const currentTrial = ref(0);
const currentLevel = ref(1);
const trials = ref([]);
const grid = ref([]);
const showingTargets = ref(false);
const selectedItems = ref([]);
const timeLeft = ref(420); // 7 minutes
const startTime = ref(0);
const score = ref(0);
const correctSequences = ref(0);
const memoryPhase = ref("showing"); // 'showing', 'waiting', 'recalling'

let mainTimer = null;

// --- Constants ---
const MAX_LEVEL = 8;
const TRIALS_PER_LEVEL = 3;
const GRID_SIZE = 4;

// --- Computed Properties ---
const progress = computed(() =>
  trials.value.length > 0 ? (currentTrial.value / trials.value.length) * 100 : 0
);
const currentTrialData = computed(() => trials.value[currentTrial.value]);

const memoryPhaseClass = computed(() => {
  switch (memoryPhase.value) {
    case "showing":
      return "bg-blue-100 text-blue-700 border-blue-300";
    case "waiting":
      return "bg-orange-100 text-orange-700 border-orange-300";
    case "recalling":
      return "bg-green-100 text-green-700 border-green-300";
    default:
      return "";
  }
});

const memoryPhaseText = computed(() => {
  switch (memoryPhase.value) {
    case "showing":
      return t("spatialMemoryTest.phaseShowing");
    case "waiting":
      return t("spatialMemoryTest.phaseWaiting");
    case "recalling":
      return t("spatialMemoryTest.phaseRecalling");
    default:
      return "";
  }
});

const instructionCardClass = computed(() => {
  switch (memoryPhase.value) {
    case "showing":
      return "from-blue-50 to-blue-100 border-blue-200";
    case "waiting":
      return "from-orange-50 to-orange-100 border-orange-200";
    case "recalling":
      return "from-green-50 to-green-100 border-green-200";
    default:
      return "";
  }
});

const instructionTextClass = computed(() => {
  switch (memoryPhase.value) {
    case "showing":
      return "text-blue-800";
    case "waiting":
      return "text-orange-800";
    case "recalling":
      return "text-green-800";
    default:
      return "";
  }
});

const instructionText = computed(() => {
  if (!currentTrialData.value) return "";
  switch (memoryPhase.value) {
    case "showing":
      return `${t("spatialMemoryTest.rememberLit")} ${
        currentTrialData.value.targets.length
      } ${t("spatialMemoryTest.positions")}`;
    case "waiting":
      return t("spatialMemoryTest.prepareToRecall");
    case "recalling":
      return t("spatialMemoryTest.clickLitPositions");
    default:
      return "";
  }
});

const results = computed(() => {
  if (stage.value !== "results") return {};
  const total = trials.value.length;
  const accuracy =
    total > 0 ? Math.round((correctSequences.value / total) * 100) : 0;

  let memorySpan = 1;
  for (let level = 1; level <= MAX_LEVEL; level++) {
    const levelTrials = trials.value.filter((t) => t.level === level);
    const levelCorrectCount = levelTrials.filter((trial, index) => {
      const trialIndex = trials.value.findIndex((t) => t.id === trial.id);
      return responsesForLevel(level).some(
        (r) => r.trialIndex === trialIndex && r.correct
      );
    }).length;

    if (levelCorrectCount >= 2) {
      // At least 2 out of 3 correct
      memorySpan = level;
    } else if (level > 1) {
      break;
    }
  }

  const finalScore = Math.min(100, Math.round(accuracy + (memorySpan - 1) * 5));
  const maxLevel =
    correctSequences.value > 0
      ? Math.max(
          ...trials.value.slice(0, correctSequences.value).map((t) => t.level)
        )
      : 0;

  return {
    finalScore,
    spatialMemorySpan: memorySpan,
    accuracy,
    correctSequences: correctSequences.value,
    maxLevel,
  };
});

// --- Methods ---
const gridItemClass = (item) => {
  if (showingTargets.value && item.isTarget) {
    return "bg-blue-500 border-blue-600 shadow-lg";
  }
  if (item.clicked) {
    return "bg-green-400 border-green-500";
  }
  return "bg-slate-100 border-slate-300 hover:bg-slate-200";
};

const generateTrial = (level, trialId) => {
  const targetCount = Math.min(level + 2, 8);
  const targets = [];
  const usedPositions = new Set();

  for (let i = 0; i < targetCount; i++) {
    let row, col;
    do {
      row = Math.floor(Math.random() * GRID_SIZE);
      col = Math.floor(Math.random() * GRID_SIZE);
    } while (usedPositions.has(`${row}-${col}`));

    usedPositions.add(`${row}-${col}`);
    targets.push({ id: i, row, col, isTarget: true, clicked: false });
  }
  return { id: trialId, targets, gridSize: GRID_SIZE, level };
};

const initializeGrid = (trial) => {
  const newGrid = [];
  for (let row = 0; row < GRID_SIZE; row++) {
    for (let col = 0; col < GRID_SIZE; col++) {
      const isTarget = trial.targets.some(
        (t) => t.row === row && t.col === col
      );
      newGrid.push({
        id: row * GRID_SIZE + col,
        row,
        col,
        isTarget,
        clicked: false,
      });
    }
  }
  return newGrid;
};

const startShowingPhase = () => {
  memoryPhase.value = "showing";
  showingTargets.value = true;
  const showTime = Math.min(3000, 1500 + currentLevel.value * 200);

  setTimeout(() => {
    showingTargets.value = false;
    memoryPhase.value = "waiting";
    setTimeout(() => {
      memoryPhase.value = "recalling";
    }, 500);
  }, showTime);
};

const handleStartTest = () => {
  stage.value = "test";
  startTime.value = Date.now();

  const newTrials = [];
  let trialIdCounter = 0;
  for (let level = 1; level <= MAX_LEVEL; level++) {
    for (let i = 0; i < TRIALS_PER_LEVEL; i++) {
      newTrials.push(generateTrial(level, trialIdCounter++));
    }
  }
  trials.value = newTrials;

  if (newTrials.length > 0) {
    const firstTrial = newTrials[0];
    grid.value = initializeGrid(firstTrial);
    currentLevel.value = firstTrial.level;
    startShowingPhase();
  }
};

const handleGridClick = (item) => {
  if (
    memoryPhase.value !== "recalling" ||
    selectedItems.value.includes(item.id)
  )
    return;

  const newSelectedItems = [...selectedItems.value, item.id];
  selectedItems.value = newSelectedItems;

  grid.value = grid.value.map((gridItem) =>
    gridItem.id === item.id ? { ...gridItem, clicked: true } : gridItem
  );

  const trial = currentTrialData.value;
  const targetIds = trial.targets.map((t) => t.row * GRID_SIZE + t.col);

  if (newSelectedItems.length === trial.targets.length) {
    const correct =
      targetIds.every((id) => newSelectedItems.includes(id)) &&
      newSelectedItems.every((id) => targetIds.includes(id));

    if (correct) {
      score.value += currentLevel.value * 10;
      correctSequences.value++;
    }

    setTimeout(() => {
      if (currentTrial.value < trials.value.length - 1) {
        const nextTrialIndex = currentTrial.value + 1;
        currentTrial.value = nextTrialIndex;
        const nextTrial = trials.value[nextTrialIndex];
        currentLevel.value = nextTrial.level;
        grid.value = initializeGrid(nextTrial);
        selectedItems.value = [];
        startShowingPhase();
      } else {
        stage.value = "results";
      }
    }, 1000);
  }
};

const handleComplete = () => {
  const res = results.value;
  emit("complete", {
    id: Date.now().toString(),
    testType: "spatial-memory",
    score: res.finalScore,
    completedAt: new Date(),
    duration: Math.round((Date.now() - startTime.value) / 1000),
    details: {
      totalTrials: trials.value.length,
      correctSequences: res.correctSequences,
      accuracy: res.accuracy,
      spatialMemorySpan: res.spatialMemorySpan,
      averageLevel:
        res.correctSequences > 0
          ? Math.round(score.value / (res.correctSequences * 10))
          : 1,
      maxLevel: res.maxLevel,
      totalScore: score.value,
    },
  });
};

// --- Lifecycle Hooks ---
watch(stage, (newStage) => {
  if (newStage === "test" && !mainTimer) {
    mainTimer = setInterval(() => {
      if (timeLeft.value <= 1) {
        stage.value = "results";
        clearInterval(mainTimer);
      } else {
        timeLeft.value--;
      }
    }, 1000);
  } else if (newStage !== "test" && mainTimer) {
    clearInterval(mainTimer);
    mainTimer = null;
  }
});

onUnmounted(() => {
  if (mainTimer) {
    clearInterval(mainTimer);
  }
});

// Helper for results calculation
const responsesForLevel = (level) => {
  const levelTrials = trials.value.filter((t) => t.level === level);
  // This is a placeholder as the original logic was flawed.
  // A more robust response tracking is needed for accurate per-level results.
  // For now, we base it on correctSequences count.
  const correctCountForLevel = Math.max(
    0,
    correctSequences.value - (level - 1) * TRIALS_PER_LEVEL
  );
  return Array.from({ length: correctCountForLevel }, (_, i) => ({
    trialIndex: (level - 1) * TRIALS_PER_LEVEL + i,
    correct: true,
  }));
};
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
